package com.example.mypic.adapters;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.mypic.R;
import com.example.mypic.models.IPWallpaperImage;

public class PicAdapter extends ArrayAdapter<IPWallpaperImage> {
	private Context context;
	private List<IPWallpaperImage> models;

	public PicAdapter(Context context, int resource,
			List<IPWallpaperImage> models) {
		super(context, resource, models);
		// TODO Auto-generated constructor stub
		this.context = context;
		this.models = models;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		View rowView = convertView;
		if (rowView == null) {
			LayoutInflater inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			rowView = inflater.inflate(R.layout.pic, parent, false);
		}
		IPWallpaperImage wall = models.get(position);
		if (wall != null) {
			try {
				ImageView ivImage = (ImageView) rowView
						.findViewById(R.id.ivImage);
				InputStream is;
				is = (InputStream) new URL(wall.getThumnaiImage())
						.getContent();

				Drawable drawable = Drawable
						.createFromStream(is, "iamge_" + position);
				ivImage.setImageDrawable(drawable);
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// download anh va hien thi len imageview
			TextView tvNo = (TextView) rowView.findViewById(R.id.tvNo);
			TextView tvView = (TextView) rowView.findViewById(R.id.tvView);
			TextView tvDown = (TextView) rowView.findViewById(R.id.tvDown);
			TextView tvWidth = (TextView) rowView.findViewById(R.id.tvWidth);
			TextView tvHeight = (TextView) rowView.findViewById(R.id.tvHeight);

			tvNo.setText((position + 1) + "");
			tvView.setText(wall.getView() + "");
			tvDown.setText(wall.getDownload() + "");
			tvWidth.setText(wall.getWidth() + "");
			tvHeight.setText(wall.getHeight() + "");
		}

		return rowView;
	}
}
